package cn.com.qingz.core.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class IDGenerator {
	
	private static IDGenerator instance;
	private String date;
	public final static SimpleDateFormat TIMESTAMP =   new SimpleDateFormat("yyyyMMddHHmmssSSS");
	public final static SimpleDateFormat TIMESTAMPSS=   new SimpleDateFormat("ssSSS");
	private long current = 0;

	private IDGenerator() {
	}

	public synchronized String nextValue(String prefix) {
		String cDate =  TIMESTAMP.format(new Date());
		if (!cDate.equals(date)) {
			date = cDate;
			current = 0;
		}
		return prefix + date + String.format("%02d", ++current);
	}

	public synchronized String nextValueShort(String prefix) {
		String cDate =  TIMESTAMPSS.format(new Date());
		if (!cDate.equals(date)) {
			date = cDate;
			current = 0;
		}
		return prefix + date + String.format("%02d", ++current);
	}
	public static IDGenerator getInstance() {
		if (instance == null) {
			synchronized (IDGenerator.class) {
				if (instance == null) {
					instance = new IDGenerator();
					instance.date = TIMESTAMP.format(new Date());
					instance.current = 0;
				}
			}
		}
		return instance;
	}
	
}
